package com.sdry.web.controller.zc;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.model.jyy.ReceiveDetail;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.MaterielInStock;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.lz.WarehouseRegion;
import com.sdry.model.lz.WarehouseRegionLocation;
import com.sdry.model.zc.ZcGeneralQueryEntity;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.cb.ReportFormService;
import com.sdry.service.lz.CustomerService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.zc.ZcInventoryManagementService;
import com.sdry.utils.BaseUtils;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;
import com.sdry.utils.ZcInventoryManagementExport;
import com.sdry.web.controller.cb.ReportFormController;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 *
 * @ClassName:    ZcWarehouseController
 * @Description:  库存管理
 * @Author:       zc
 * @CreateDate:   2019年4月2日 下午5:55:37   
 * @Version:      v1.0
 */
@RequestMapping("inventoryManagement")
@Controller
public class ZcInventoryManagementController {
	public static final Integer AFFECT_ROW = 0;
	@Resource
	private ZcInventoryManagementService zcInventoryManagementService;
	@Resource
	private MaterielService materielService;
	@Resource
	CustomerService  customerService;

	@Autowired
	private ReportFormService reportFormService;

	public static Logger logger = LogManager.getLogger(ReportFormController.class);


	/**
	 * 进入库存管理页面
	 * @param session
	 * @return
	 */
	@RequestMapping("enterInventoryManagement")
	public ModelAndView enterInventoryManagement(Model model,HttpSession session,HttpServletResponse response){
		ZcSysUserEntity staf = (ZcSysUserEntity) session.getAttribute("user");
		if(staf.getRoleId().equals("20010,")) {
			Customer customer=customerService.queryCustomerlxrById(staf.getCustomer_id());
			model.addAttribute("cname", customer.getCustomer_name());
			model.addAttribute("cid", staf.getCustomer_id());
			model.addAttribute("lname", customer.getContacts_name());
			ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
			//查询所有供应商
			List<Customer> allCustomerList = zcInventoryManagementService.selectAllCustomerList(zcGeneralQueryEntity);
			List<Warehouse> allWarehouseList = zcInventoryManagementService.selectAllWarehouseList(zcGeneralQueryEntity);
			ModelAndView mav = new ModelAndView();
			mav.addObject("allCustomerList",allCustomerList);
			mav.addObject("allWarehouseList",allWarehouseList);
			mav.setViewName("/zc/warehouse/inventoryManagement2");
			return mav;
		}else {
			ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
			//查询所有供应商
			List<Customer> allCustomerList = zcInventoryManagementService.selectAllCustomerList(zcGeneralQueryEntity);
			List<Warehouse> allWarehouseList = zcInventoryManagementService.selectAllWarehouseList(zcGeneralQueryEntity);
			ModelAndView mav = new ModelAndView();
			mav.addObject("allCustomerList",allCustomerList);
			mav.addObject("allWarehouseList",allWarehouseList);
			mav.setViewName("/zc/warehouse/inventoryManagement");
			return mav;
		}
	}
	/**
	 * 进入精简库存管理页面
	 * @param session
	 * @return
	 */
	@RequestMapping("enterInventoryManagementOnlyCount")
	public ModelAndView enterInventoryManagementOnlyCount(Model model,HttpSession session,HttpServletResponse response){
		ZcSysUserEntity staf = (ZcSysUserEntity) session.getAttribute("user");
		if(staf.getRoleId().equals("20010,")) {
			Customer customer=customerService.queryCustomerlxrById(staf.getCustomer_id());
			model.addAttribute("cname", customer.getCustomer_name());
			model.addAttribute("cid", staf.getCustomer_id());
			model.addAttribute("lname", customer.getContacts_name());
			ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
			//查询所有供应商
			List<Customer> allCustomerList = zcInventoryManagementService.selectAllCustomerList(zcGeneralQueryEntity);
			List<Warehouse> allWarehouseList = zcInventoryManagementService.selectAllWarehouseList(zcGeneralQueryEntity);
			ModelAndView mav = new ModelAndView();
			mav.addObject("allCustomerList",allCustomerList);
			mav.addObject("allWarehouseList",allWarehouseList);
			mav.setViewName("/zc/warehouse/inventoryManagementOnlyCount2");
			return mav;
		}else {
			ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
			//查询所有供应商
			List<Customer> allCustomerList = zcInventoryManagementService.selectAllCustomerList(zcGeneralQueryEntity);
			List<Warehouse> allWarehouseList = zcInventoryManagementService.selectAllWarehouseList(zcGeneralQueryEntity);
			ModelAndView mav = new ModelAndView();
			mav.addObject("allCustomerList",allCustomerList);
			mav.addObject("allWarehouseList",allWarehouseList);
			mav.setViewName("/zc/warehouse/inventoryManagementOnlyCount");
			return mav;
		}
	}
	/**
	 * 查询库存信息
	 * @param response
	 * @param zcGeneralQueryEntity
	 */
	@RequestMapping("selectInventoryInfoList")
	public void selectInventoryInfoList(HttpServletResponse response, ZcGeneralQueryEntity zcGeneralQueryEntity){
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		List<ZcInventoryInfoEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoList(zcGeneralQueryEntity);
		int count = zcInventoryManagementService.countInventoryInfoList(zcGeneralQueryEntity);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(inventoryInfoList, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("selectInventoryInfoList1")
	public void selectInventoryInfoList1(HttpServletResponse response, String cid,String num,ZcGeneralQueryEntity zcGeneralQueryEntity){
		if(cid!=null&&num!=null) {
			String s="m.customer_id ="+cid+" and m.materiel_num like" +num+" and";
			zcGeneralQueryEntity.setStrWhere(s);
		}else {

			String s="m.customer_id ="+cid+" and";
			zcGeneralQueryEntity.setStrWhere(s);

		}
		List<ZcInventoryInfoEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoList(zcGeneralQueryEntity);
		int count = zcInventoryManagementService.countInventoryInfoList(zcGeneralQueryEntity);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(inventoryInfoList, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 查询精简库存信息，多仓库版本 cb_2019年11月8日09:46:34
	 * @param response
	 * @param zcGeneralQueryEntity
	 */
	@RequestMapping("selectInventoryInfoOnlyCountList")
	public void selectInventoryInfoOnlyCountList(HttpServletResponse response, ZcGeneralQueryEntity zcGeneralQueryEntity){
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		logger.info("查询精简库存信息，多仓库版本 cb_2019年11月8日09:46:34  ZcGeneralQueryEntity="+JSONArray.fromObject(zcGeneralQueryEntity));
		List<ZcInventoryInfoEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoOnlyCountList(zcGeneralQueryEntity);
		int count = zcInventoryManagementService.countInventoryInfoOnlyCountList(zcGeneralQueryEntity);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(inventoryInfoList, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("selectInventoryInfoOnlyCountList1")
	public void selectInventoryInfoOnlyCountList1(HttpServletResponse response ,String cid,String num,ZcGeneralQueryEntity zcGeneralQueryEntity){
		if(cid!=null&&num!=null) {
			String s="m.customer_id ="+cid+" and m.materiel_num like" +num+" and";
			zcGeneralQueryEntity.setStrWhere(s);
		}else {

			String s="m.customer_id ="+cid+" and";
			zcGeneralQueryEntity.setStrWhere(s);

		}
		List<ZcInventoryInfoEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoOnlyCountList(zcGeneralQueryEntity);
		int count = zcInventoryManagementService.countInventoryInfoOnlyCountList(zcGeneralQueryEntity);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(inventoryInfoList, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 查询库存信息详情
	 * @param response
	 * @param zcGeneralQueryEntity
	 */
	@RequestMapping("selectInventoryInfoListDetails")
	public void selectInventoryInfoListDetails(
			HttpServletResponse response,
			ZcGeneralQueryEntity zcGeneralQueryEntity,
			String enterDate,
			String userName
	){
		List<ZcMaterielAndTrayEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoListDetails(zcGeneralQueryEntity);

		for (ZcMaterielAndTrayEntity ze : inventoryInfoList) {
			ze.setNew_materiel_code_list(userName);
			ze.setBinding_date(enterDate);
		}

		int count = zcInventoryManagementService.countInventoryInfoListDetails(zcGeneralQueryEntity);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(inventoryInfoList, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询库存信息详情
	 * @param response
	 * @param zcGeneralQueryEntity
	 */
	@RequestMapping("selectInventoryInfoListKuWei")
	public void selectInventoryInfoListKuWei(HttpServletResponse response,ZcGeneralQueryEntity zcGeneralQueryEntity){
		List<ZcMaterielAndTrayEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoListDetails(zcGeneralQueryEntity);
		int count = zcInventoryManagementService.countInventoryInfoListDetails(zcGeneralQueryEntity);
		List<ZcMaterielAndTrayEntity> list1 = removeDuplicateOutputField(inventoryInfoList);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 0);
		jsonObject.put("data", list1);
		jsonObject.put("count", list1.size());
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static List<ZcMaterielAndTrayEntity> removeDuplicateOutputField(List<ZcMaterielAndTrayEntity> list) {
		Set<ZcMaterielAndTrayEntity> set = new TreeSet<>(new Comparator<ZcMaterielAndTrayEntity>() {
			@Override
			public int compare(ZcMaterielAndTrayEntity o1, ZcMaterielAndTrayEntity o2) {
				int compareToResult = 1;//==0表示重复
				if (StringUtils.equals(o1.getZcTrayAndLocation().getRegion_name(), o2.getZcTrayAndLocation().getRegion_name())) {
					compareToResult = 0;

					return compareToResult;
				}

				return 0;
			}
		});

		set.addAll(list);
		return new ArrayList<>(set);
	}



	/**
	 * 通过仓库id查库区
	 * @param response
	 * @param zcGeneralQueryEntity
	 */
	@RequestMapping("selectWarehouseRegionListByWarehouseId")
	public void selectWarehouseRegionListByWarehouseId(HttpServletResponse response, ZcGeneralQueryEntity zcGeneralQueryEntity){
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		List<WarehouseRegion> warehouseRegionList = zcInventoryManagementService.selectWarehouseRegionListByWarehouseId(zcGeneralQueryEntity);
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(warehouseRegionList, jsonConfig);
		try {
			ResponseUtil.write(response, jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 通过库区id查库位
	 * @param response
	 * @param zcGeneralQueryEntity
	 */
	@RequestMapping("selectWarehouseRegionLocationListByRegionId")
	public void selectWarehouseRegionLocationListByRegionId(HttpServletResponse response, ZcGeneralQueryEntity zcGeneralQueryEntity){
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		List<WarehouseRegionLocation> warehouseRegionLocationList = zcInventoryManagementService.selectWarehouseRegionLocationListByRegionId(zcGeneralQueryEntity);
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(warehouseRegionLocationList, jsonConfig);
		try {
			ResponseUtil.write(response, jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 通过产品码或简码查询物料规格型号信息
	 * @param response
	 * @param zcGeneralQueryEntity
	 */
	@RequestMapping("selectMaterielSizeByCode")
	public void selectMaterielSizeByCode(HttpServletResponse response, ZcGeneralQueryEntity zcGeneralQueryEntity){
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		List<Materiel> materiel = zcInventoryManagementService.selectMaterielSizeByCode(zcGeneralQueryEntity);
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(materiel, jsonConfig);
		try {
			ResponseUtil.write(response, jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 通过产品码或简码查询库存信息
	 * @param response
	 * @param zcGeneralQueryEntity
	 */
	@RequestMapping("selectInventoryInfoByCode")
	public void selectInventoryInfoByCode(HttpServletResponse response, ZcGeneralQueryEntity zcGeneralQueryEntity){
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		List<ZcInventoryInfoEntity> inventoryInfo = zcInventoryManagementService.selectInventoryInfoByCode(zcGeneralQueryEntity);
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(inventoryInfo, jsonConfig);
		try {
			ResponseUtil.write(response, jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 调整
	 * @param response
	 * @param inventId
	 * @param mNum
	 */
	@RequestMapping("adjust")
	public void adjust(HttpServletResponse response, String inventId, String mNum){
		int affact = zcInventoryManagementService.adjust(inventId,mNum);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 库存预警
	 * @param response
	 * @param zcInventoryInfoEntity
	 */
	@RequestMapping("stockWarning")
	public void stockWarning(HttpServletResponse response,ZcInventoryInfoEntity zcInventoryInfoEntity){
		int affact = zcInventoryManagementService.stockWarning(zcInventoryInfoEntity);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 移库
	 * @param response
	 */
	@RequestMapping("bindingWarehouse")
	public void bindingWarehouse(HttpServletResponse response,Materiel materiel){
		int affact = zcInventoryManagementService.bindingWarehouse(materiel);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*******************************************APP***********************************************/

	/**
	 * 通过产品码或简码查询物料规格型号信息
	 * @param response
	 * @param mcode 产品码或简码
	 */
	@RequestMapping("selectMaterielSizeByCodeApp")
	public void selectMaterielSizeByCodeApp(HttpServletResponse response, String mcode){
		mcode = "'"+mcode+"'";
		String empty = "''";
		String strWhere = "";
		ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
		strWhere = "(m.materiel_num = "+mcode+" or brevity_num = "+mcode+" or m.devanning_code = "+mcode+") and ";
		zcGeneralQueryEntity.setStrWhere(strWhere);
		List<Materiel> materiel = zcInventoryManagementService.selectMaterielSizeByCode(zcGeneralQueryEntity);
		JSONObject jsonObject = new JSONObject();
		if(materiel.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", materiel);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 通过产品码或简码查询物料规格型号信息2
	 * @param response
	 * @param mcode 产品码或简码
	 * @param specification 物料规格型号
	 */
	@RequestMapping("selectMaterielSizeByCodeApp2")
	public void selectMaterielSizeByCodeApp2(HttpServletResponse response, String mcode, String specification){
		String[] sizeAndProperties = specification.split("/");
		List<MaterielInStock> materiel = zcInventoryManagementService.queryMaterielBatchByMcodeSpecification(mcode, sizeAndProperties[0], sizeAndProperties[1]);
		if (materiel.size() > 0) {
			//根据物料ID去收货详细表查询
			List<ReceiveDetail> receiveDetail = zcInventoryManagementService.queryReceiveDetailByMaterielId(materiel.get(0).getId());
			for (int i = 0; i < receiveDetail.size(); i++) {
				//System.out.println(materiel.get(0).getBatch());
				//System.out.println(receiveDetail.get(i).getPici());
				materiel.get(0).getBatch().add(receiveDetail.get(i).getPici());
			}
		}
		JSONObject jsonObject = new JSONObject();
		if(materiel.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", materiel);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 通过产品码或简码、规格、型号查询物料信息
	 */
	@RequestMapping("selectMaterielInfoByCodeApp")
	public void selectMaterielInfoByCodeApp(HttpServletResponse response, String json){
		Gson gson = new Gson();
		Materiel materiel= gson.fromJson(json,new TypeToken<Materiel>() {}.getType());
		String materiel_num = "'"+materiel.getMateriel_num()+"'";
		String materiel_size = "'"+materiel.getMateriel_size().split("/")[0]+"'";
		String materiel_properties = "'"+materiel.getMateriel_size().split("/")[1]+"'";
		String empty = "''";
		String strWhere = "";
		ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
		strWhere = "(m.materiel_num = "+materiel_num+" or m.brevity_num = "+materiel_num+" or m.devanning_code = "+materiel_num+") and m.materiel_size = "+materiel_size+" and m.materiel_properties = "+materiel_properties+" and ";
		zcGeneralQueryEntity.setStrWhere(strWhere);
		Materiel materielInfo = zcInventoryManagementService.selectMaterielInfoByCodeApp(zcGeneralQueryEntity);
		JSONObject jsonObject = new JSONObject();
		if(materielInfo!=null){
			jsonObject.put("status", "1");
			jsonObject.put("data", materielInfo);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 查仓库库区
	 * @param response
	 * @param customer_id
	 */
	@RequestMapping("selectWarehouseRegionListApp")
	public void selectWarehouseRegionListApp(HttpServletResponse response, String customer_id){
		ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
		List<Warehouse> zcWareTreeList = zcInventoryManagementService.selectAllWarehouseList(zcGeneralQueryEntity);
		for (Warehouse warehouse : zcWareTreeList) {
			String strWhere = "r.warehouse_id = "+ warehouse.getId() + " and cw.cid = "+customer_id+" and cw.is_empty = 0 and ";
			zcGeneralQueryEntity.setStrWhere(strWhere);
			List<WarehouseRegion> warehouseRegionList = zcInventoryManagementService.selectWarehouseRegionListByWarehouseId(zcGeneralQueryEntity);
			warehouse.setWarehouseRegion(warehouseRegionList);
		}
		JSONObject jsonObject = new JSONObject();
		if(zcWareTreeList.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", zcWareTreeList);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
	/**
	 * 移库
	 * @param response
	 * @param id
	 */
	@RequestMapping("appMove")
	public void appMove(HttpServletResponse response,String id,String src_region_id,String region_id){
		Materiel materiel= new Materiel();
		materiel.setId(Long.parseLong(id));
		materiel.setSrc_region_id(Long.parseLong(src_region_id));
		materiel.setRegion_id(Long.parseLong(region_id));
		int affact = zcInventoryManagementService.bindingWarehouse(materiel);
		JSONObject jsonObject = new JSONObject();
		if(affact > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", "提交成功");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "提交失败");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 查询库存预警列表
	 * @param response
	 */
	@RequestMapping("selectStockWarningList")
	public void selectStockWarningList(HttpServletResponse response){
		List<ZcInventoryInfoEntity> selectStockWarningList = zcInventoryManagementService.selectStockWarningList();
		JSONObject jsonObject = new JSONObject();
		if(selectStockWarningList.size() > AFFECT_ROW){
			jsonObject.put("status", "1");
			jsonObject.put("data", selectStockWarningList);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 导出Excel
	 * @param response
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	@RequestMapping("/doExportall")
	public void doExportall(HttpServletResponse response, HttpServletRequest request, String strWhere,ZcGeneralQueryEntity zcGeneralQueryEntity) throws UnsupportedEncodingException{
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		zcGeneralQueryEntity.setPage(1);
		zcGeneralQueryEntity.setLimit(100000);
		List<ZcInventoryInfoEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoList(zcGeneralQueryEntity);
		ZcGeneralQueryEntity zcGeneralQueryEntity2=new ZcGeneralQueryEntity();
		//List<List<String>> lists = zhuanlist(inventoryInfoList,zcGeneralQueryEntity2);
		List<List<String>> lists = ZcInventoryManagementExport.exportList(getErgodicZcInventoryManagement(inventoryInfoList));
		ExcelUtils.export("库存所有数据",namess(), response, lists);
	}

	public List<ZcInventoryInfoEntity> getErgodicZcInventoryManagement(List<ZcInventoryInfoEntity> inventoryInfoList) {
		List<ZcInventoryInfoEntity> list = new ArrayList<>();
		ma:for (ZcInventoryInfoEntity infoEntity : inventoryInfoList) {
			String customer_name =infoEntity.getMateriel().getCustomer().getCustomer_name();
			String mid = infoEntity.getMid().toString();
			List<Materiel> infoDetailedList = reportFormService.getStockInventoryInfoDetailedList(mid, "2", 1, 100000);
			for (Materiel materiel : infoDetailedList) {
				//库区名称
				String materielRemark = materiel.getRemark();
				List<Materiel> tiaoMaList = reportFormService.getTiaoMaList("2", mid, materiel.getRemark());
				for (Materiel tiaoma : tiaoMaList) {
					//客户
					//条码
					Materiel materiel1 = new Materiel();
					materiel1.setOutgoing_frequency(tiaoma.getMateriel_num());
					materiel1.setUnit(tiaoma.getUnit());
					materiel1.setRegion_name(materielRemark);
					materiel1.setCustomer_name(customer_name);
					//条码对应时间
					if (StringUtil.isEmpty(tiaoma.getOut_date())) {
						String createDate = reportFormService.getTiaomaOut_date(tiaoma.getMateriel_num());
						materiel1.setOut_date(createDate);
					}else {
						materiel1.setOut_date(tiaoma.getOut_date());
					}


					materiel1.setMateriel_name(infoEntity.getMateriel().getMateriel_name());
					materiel1.setMateriel_num(infoEntity.getMateriel().getMateriel_num());
					ZcInventoryInfoEntity zcInventoryInfoEntity = new ZcInventoryInfoEntity();
					// 条码收货时间
					zcInventoryInfoEntity.setEnterDate(infoEntity.getEnterDate());
					// 收货操作人;
					zcInventoryInfoEntity.setReason(infoEntity.getZcSysUser().getUserName());
					zcInventoryInfoEntity.setMateriel(materiel1);
					list.add(zcInventoryInfoEntity);
				}
			}
		}
		return list;
	}
	public List<String> namess() {
		List<String> list = new ArrayList<>();

		list.add("序号");
		list.add("供应商");
		list.add("物料名称");
		list.add("SAP料号");
		list.add("库位");
		list.add("条码");
		list.add("条码对应数量");
		list.add("条码创建时间");
		list.add("条码收货时间");
		list.add("收货操作人");

        /*list.add("序号");
        list.add("供应商");
        list.add("物料名称");
        list.add("产品码");
        list.add("物料规格");
        list.add("物料型号");
        list.add("单位");
        list.add("批次");
        list.add("数量");
        list.add("总库存");
        list.add("库存上限");
        list.add("库存下限");
        list.add("所属库区");
        list.add("入库日期");
        list.add("入库人");*/
		return list;
	}

	public List<List<String>> zhuanlist ( List<ZcInventoryInfoEntity> inventoryInfoList,  ZcGeneralQueryEntity zcGeneralQueryEntity2) throws UnsupportedEncodingException{

		{
			List<List<String>> lists = new ArrayList<>();
			for (ZcInventoryInfoEntity inventoryOrder : inventoryInfoList) {
				List<String> list = new ArrayList<>();
				list.add(String.valueOf(inventoryOrder.getId()));
				list.add(inventoryOrder.getMateriel().getCustomer().getCustomer_name());
				list.add(inventoryOrder.getMateriel().getMateriel_name());
				list.add(inventoryOrder.getMateriel().getMateriel_num());
				list.add(inventoryOrder.getMateriel().getMateriel_size());
				list.add(inventoryOrder.getMateriel().getMateriel_properties());

				list.add(inventoryOrder.getMateriel().getUnit());
				list.add(inventoryOrder.getmBatch());
				list.add(String.valueOf((inventoryOrder.getmNum())));
				list.add(String.valueOf((inventoryOrder.getCountAll())));
				list.add(String.valueOf((inventoryOrder.getMateriel().getUpper_value())));

				list.add(String.valueOf((inventoryOrder.getMateriel().getLower_value())));
				if(null != inventoryOrder.getMateriel().getRegion()){
					list.add(String.valueOf((inventoryOrder.getMateriel().getRegion().getRegion_name())));
				}else{
					list.add("");
				}
				list.add(String.valueOf((inventoryOrder.getEnterDate())));
				list.add(String.valueOf((inventoryOrder.getZcSysUser().getUserName())));
				lists.add(list);

		    /*List<String> listd = new ArrayList<>();
            listd.add("库存的详情表");
            lists.add(listd);
            List<String> listn = new ArrayList<>();
            listn.add("序号");
            listn.add("库区名称");
            listn.add("库存数量");
            listn.add("库位条码");
            listn.add("物料条码");
            listn.add("物料数量");
            lists.add(listn);
            String strWhere="";
            if(inventoryOrder.getmBatch() == "''"){
		 		strWhere = " mt.mid = "+inventoryOrder.getMid() +" and ";
			} else {
				 strWhere = " mt.mid = "+inventoryOrder.getMid() +" and mt.mBatch = "+inventoryOrder.getmBatch()+" and ";
			}
            zcGeneralQueryEntity2.setStrWhere(strWhere);
            zcGeneralQueryEntity2.setPage(1);
            zcGeneralQueryEntity2.setLimit(10000);
            List<ZcMaterielAndTrayEntity> inventoryDetailList = zcInventoryManagementService.selectInventoryInfoListDetails(zcGeneralQueryEntity2);
            int i=0;
            for (ZcMaterielAndTrayEntity detail : inventoryDetailList) {
            	 List<String> list1 = new ArrayList<>();
            	
            	 list1.add(String.valueOf(i++));
              
                 list1.add(detail.getZcTrayAndLocation().getRegion_name());
                 list1.add(detail.getZcTrayAndLocation().getLocation_code());
                 list1.add(detail.getMateriel_code());
                 list1.add(String.valueOf(detail.getmNum()));
             
                 lists.add(list1);
                 list1 = null;
			}*/
				list = null;
			}
			return lists;
		}
	}
	/**
	 * 个人信息上传
	 * @return {Result}
	 */
	@RequestMapping(value = "/upload", method = {RequestMethod.POST})
	@ResponseBody
	public Object headImg(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {

		String prefix="";
		String dateStr="";
		Date now = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		//保存上传
		OutputStream out = null;
		InputStream fileInput=null;
		try{
			if(file!=null){
				String originalName = file.getOriginalFilename();
				prefix=originalName.substring(originalName.lastIndexOf(".")+1);
				dateStr = format.format(new Date());
				String filepath = "E:\\upload\\images\\" + dateStr + "." + prefix;
				File files=new File(filepath);
				//打印查看上传路径
				//System.out.println(filepath);
				if(!files.getParentFile().exists()){
					files.getParentFile().mkdirs();
				}
				file.transferTo(files);
			}
		}catch (Exception e){
		}finally{
			try {
				if(out!=null){
					out.close();
				}
				if(fileInput!=null){
					fileInput.close();
				}
			} catch (IOException e) {
			}
		}
		Map<String,Object> map2=new HashMap<>();
		Map<String,Object> map=new HashMap<>();
		map.put("code",0);
		map.put("msg","");
		map.put("data",map2);
		map2.put("src","E:\\upload\\images\\" + dateStr + "." + prefix);
		return map;
	}
	@RequestMapping("/upDownlodeFile")
	public void  down(String down,HttpServletRequest request, HttpServletResponse response) throws Exception{
		Date now = new Date();
		// 可以方便地修改日期格式
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String[] filesPath = down.split(",");
		String nowtime = dateFormat.format(now);
		for(int i = 0; i < filesPath.length; i++){
			/*String paths = "C:\\Users\\Administrator\\git\\beijing_mission_edition\\WebContent\\upload\\"
					+ filesPath[i].substring(filesPath[i].lastIndexOf("/")+1, filesPath[i].length());*/
			String paths = filesPath[i];
			File outfile = new File(paths);
			if (outfile.exists()) {
				int pos = outfile.getName().lastIndexOf(".");
				String fileext = outfile.getName().substring(pos);
				// 获取文件名称
				String filename = nowtime + i + fileext;
				InputStream fis = new BufferedInputStream(new FileInputStream(paths));
				byte[] buffer = new byte[fis.available()];
				//读取文件流
				fis.read(buffer);
				//返回头 文件名
				response.addHeader("Content-Disposition", "attachment;filename="
						+ new String(filename.replaceAll(" ", "").getBytes("utf-8"),
						"iso8859-1"));
				//返回头 文件大小
				response.addHeader("Content-Length", "" + outfile.length());
				//设置数据种类
				response.setContentType("application/octet-stream");
				//获取返回体输出权
				OutputStream os = new BufferedOutputStream(response.getOutputStream());
				//System.out.println(response.getOutputStream());
				// 输出文件
				os.write(buffer);
				fis.close();
				os.flush();
				os.close();
			}
		}
	}
	/**
	 * 导出Excel
	 * @param response
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	@RequestMapping("/doExportallonly")
	public void doExportallonly(HttpServletResponse response, HttpServletRequest request, String strWhere,ZcGeneralQueryEntity zcGeneralQueryEntity) throws UnsupportedEncodingException{
		if(zcGeneralQueryEntity.getStrWhere() == null){
			zcGeneralQueryEntity.setStrWhere("");
		}
		//System.out.println(request.getParameter(strWhere));
		zcGeneralQueryEntity.setPage(1);
		zcGeneralQueryEntity.setLimit(100000);
		List<ZcInventoryInfoEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoOnlyCountList(zcGeneralQueryEntity);
		ZcGeneralQueryEntity zcGeneralQueryEntity2=new ZcGeneralQueryEntity();
		List<List<String>> lists = zhuanlist1(inventoryInfoList,zcGeneralQueryEntity2);
		ExcelUtils.export("精简库存所有数据",namess1(), response, lists);
	}
	
	@RequestMapping("/doExportallonlyFromLian")
	public void doExportallonlyFromLian(HttpServletResponse response, HttpServletRequest request, Materiel materiel){
		logger.info("查询精简库存信息，多仓库版本 cb_2019年11月8日09:46:34  ZcGeneralQueryEntity="+JSONArray.fromObject(materiel));
		//仓库id
	    Long wareHouseId = BaseUtils.getSession();
	    materiel.setWareHouseId(wareHouseId);
	    materiel.setPage(1);
	    materiel.setPageSize(1000000);
		List<ZcInventoryInfoEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoOnlyCountListFromLian(materiel);
		ZcGeneralQueryEntity zcGeneralQueryEntity2=new ZcGeneralQueryEntity();
		List<List<String>> lists;
		try {
			lists = zhuanlist1(inventoryInfoList,zcGeneralQueryEntity2);
			ExcelUtils.export("精简库存所有数据",namess1(), response, lists);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public List<String> namess1() {
		List<String> list = new ArrayList<>();
		list.add("序号");
		list.add("供应商");
		list.add("物料名称");
		list.add("产品码");

		list.add("批次");
		list.add("良品数量");

		list.add("良品总库存");
		list.add("损溢");
		list.add("不良品数量");
		list.add("不良品总库存");
		list.add("总库存");

//		list.add("单位");
//
//		list.add("入库日期");
//
//		list.add("入库人");

		return list;
	}

	public List<List<String>> zhuanlist1 ( List<ZcInventoryInfoEntity> inventoryInfoList,  ZcGeneralQueryEntity zcGeneralQueryEntity2){
		{
			List<List<String>> lists = new ArrayList<>();
			int count=0;
			if(inventoryInfoList != null && inventoryInfoList.size() > 0){
				for (ZcInventoryInfoEntity inventoryOrder : inventoryInfoList) {
					List<String> list = new ArrayList<>();
					++count;
					list.add(String.valueOf(count));
					list.add(inventoryOrder.getMateriel().getCustomer().getCustomer_name());
					list.add(inventoryOrder.getMateriel().getMateriel_name());
					list.add(inventoryOrder.getMateriel().getMateriel_num());

					list.add(inventoryOrder.getmBatch());
					list.add(String.valueOf((inventoryOrder.getmNum())));
					list.add(String.valueOf((inventoryOrder.getCountAll())));
					list.add(String.valueOf((inventoryOrder.getmNumProfitAndLoss())));

					list.add(String.valueOf((inventoryOrder.getmNumRejects())));
					list.add(String.valueOf((inventoryOrder.getCountAllRejects())));
					list.add(String.valueOf((inventoryOrder.getCountAll()+inventoryOrder.getCountAllRejects())));
//					list.add(inventoryOrder.getMateriel().getUnit());
//					list.add(String.valueOf((inventoryOrder.getEnterDate())));
//					list.add(String.valueOf((inventoryOrder.getZcSysUser().getUserName())));
					lists.add(list);

			    /*List<String> listd = new ArrayList<>();
	            listd.add("库存的详情表");
	            lists.add(listd);
	            List<String> listn = new ArrayList<>();
	            listn.add("序号");
	            listn.add("库区名称");
	            listn.add("库存数量");
	            listn.add("库位条码");
	            listn.add("物料条码");
	            listn.add("物料数量");
	            lists.add(listn);
	            String strWhere="";
	            if(inventoryOrder.getmBatch() == "''"){
			 		strWhere = " mt.mid = "+inventoryOrder.getMid() +" and ";
				} else {
					 strWhere = " mt.mid = "+inventoryOrder.getMid() +" and mt.mBatch = "+inventoryOrder.getmBatch()+" and ";
				}
	            zcGeneralQueryEntity2.setStrWhere(strWhere);
	            zcGeneralQueryEntity2.setPage(1);
	            zcGeneralQueryEntity2.setLimit(10000);
	            List<ZcMaterielAndTrayEntity> inventoryDetailList = zcInventoryManagementService.selectInventoryInfoListDetails(zcGeneralQueryEntity2);
	            int i=0;
	            for (ZcMaterielAndTrayEntity detail : inventoryDetailList) {
	            	 List<String> list1 = new ArrayList<>();
	            	
	            	 list1.add(String.valueOf(i++));
	              
	                 list1.add(detail.getZcTrayAndLocation().getRegion_name());
	                 list1.add(detail.getZcTrayAndLocation().getLocation_code());
	                 list1.add(detail.getMateriel_code());
	                 list1.add(String.valueOf(detail.getmNum()));
	             
	                 lists.add(list1);
	                 list1 = null;
				}*/
					list = null;
				}
			}
			
			return lists;
		}
	}
	
	/**
	 * 查询精简库存信息，多仓库版本 
	 * @param response
	 * @param materiel
	 */
	@RequestMapping("selectInventoryInfoOnlyCountListFromLian")
	public void selectInventoryInfoOnlyCountListFromLian(HttpServletResponse response, Materiel materiel){
		logger.info("查询精简库存信息，多仓库版本 cb_2019年11月8日09:46:34  ZcGeneralQueryEntity="+JSONArray.fromObject(materiel));
		//仓库id
	    Long wareHouseId = BaseUtils.getSession();
	    materiel.setWareHouseId(wareHouseId);
		List<ZcInventoryInfoEntity> inventoryInfoList = zcInventoryManagementService.selectInventoryInfoOnlyCountListFromLian(materiel);
		int count = zcInventoryManagementService.countInventoryInfoOnlyCountListFromLian(materiel);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(inventoryInfoList, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

